"""Add unique constraint for custom task name per user

Revision ID: add_unique_constraint_custom_task_name
Revises: 
Create Date: 2024-01-01 00:00:00.000000

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'add_unique_constraint_custom_task_name'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    """Add unique constraint for custom task name per user"""
    # 首先删除重复的任务（保留最新的）
    op.execute("""
        DELETE FROM custom_task 
        WHERE id NOT IN (
            SELECT MAX(id) 
            FROM custom_task 
            GROUP BY name, user_id
        )
    """)
    
    # 添加唯一约束
    op.create_unique_constraint(
        'unique_task_name_per_user',
        'custom_task',
        ['name', 'user_id']
    )

def downgrade():
    """Remove unique constraint for custom task name per user"""
    op.drop_constraint('unique_task_name_per_user', 'custom_task', type_='unique')